<?php
declare(strict_types=1);
namespace cms\system\admin\mvc_controller;

use Hyperf\Contract\ConfigInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Contract\ContainerInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\View\RenderInterface;

abstract class AbstractController {
    /**
     * @Inject()
     * @var ContainerInterface
     */
    protected ContainerInterface $container;

    /**
     * @Inject()
     * @var RequestInterface
     */
    protected RequestInterface $request;

    /**
     * @Inject()
     * @var ResponseInterface
     */
    protected ResponseInterface $response;

    /**
     * @Inject()
     * @var ConfigInterface
     */
    protected ConfigInterface $config;

    /**
     * @Inject()
     * @var RenderInterface
     */
    protected RenderInterface $view;

    /**
     * 模板处理
     * @param array $data
     * @param string $template
     * @param string $theme
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function template(array $data = [], string $template = '', string $theme = ''): \Psr\Http\Message\ResponseInterface
    {
        // 模板路径
        $template_path = '';
        // 模板名称
        $template_name = '';
        if ($template && strpos($template, '/') === 0) {
            // TODO 加载绝对路径模板
        }
        // 取得路由回调
        $callback = ($this->request->getAttribute('Hyperf\\HttpServer\\Router\\Dispatched'))->handler->callback;
        // 命名空间
        $namespace = $callback[0];
        // 操作方法
        $action = $callback[1];
        $namespace_array = explode('\\', $namespace);
        foreach ($namespace_array as $k => $v) {
            if ($v && stripos($v, 'mvc_controller') === false && stripos($v, 'Controller') === false) {
                $template_path .= $v.DIRECTORY_SEPARATOR;
            }
            if (strpos($v, 'Controller')) {
                $template_name .= substr($v, 0, strpos($v, 'Controller'));
            }
        }
        $template_path .= $this->config->get('view.config.view_directory', 'template').DIRECTORY_SEPARATOR.$this->config->get('view.config.view_theme', 'theme_default').DIRECTORY_SEPARATOR;
        if ($template_name) {
            $template_name = strtolower(preg_replace('/([a-z])([A-Z])/', "$1_$2", $template_name));
        }
        if ($template) {
            $template = $template_name.'_'.$template;
        } else {
            $template = $template_name.'_'.$action;
        }
        return $this->view->render($template_path.$template, $data);
    }
}